/*
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

#include "TcpPort.h"
#include <QApplication>

using namespace std;
using namespace SerialPortClass;
TcpPort::TcpPort(QObject *parent)
    : PortBase(parent),
      tcpPortWork(nullptr),
      witeThreadMsgId(0),
      oneTimeReadByte(0)
{
    tcpPortWork = new TcpPortWork();
    connect(tcpPortWork, &TcpPortWork::SignalReadData, this, &TcpPort::SlotReadData, Qt::DirectConnection);
    connect(this, &TcpPort::SignalWriteToPort, tcpPortWork, &TcpPortWork::SlotWriteToPort, Qt::DirectConnection);
}

TcpPort::~TcpPort()
{
    if (tcpPortWork != nullptr) {
        tcpPortWork->ClosePort();
        tcpPortWork->quit();
        tcpPortWork->wait();
        delete tcpPortWork;
        tcpPortWork = nullptr;
    }
}

bool TcpPort::InitPort(PortBaseInitStru &tcpPortInit)
{
    if (tcpPortWork == nullptr) {
        return false;
    }
    witeThreadMsgId = tcpPortInit.witeThreadMsgId;
    oneTimeReadByte = tcpPortInit.oneTimeReadByte;
    if (!tcpPortWork->InitPort(tcpPortInit)) {
        return false;
    }
    return true;
}

BOOL TcpPort::StartMonitoring()
{
    if (tcpPortWork == nullptr) {
        return false;
    }
    tcpPortWork->start();
    return true;
}

void TcpPort::SlotReadData(WPARAM wParam, LPARAM lParam)
{
    emit SignalSendMsg(witeThreadMsgId, wParam, lParam);
}

void TcpPort::WriteToPort(const char *string, int n)
{
    SignalWriteToPort(string, n);
}

bool TcpPort::IsThreadAlive() const
{
    if (tcpPortWork == nullptr) {
        return false;
    }
    return tcpPortWork->IsThreadAlive();
}

void TcpPort::SetOneTimeReadByte(DWORD readByte)
{
    if (tcpPortWork != nullptr) {
        tcpPortWork->SetOneTimeReadByte(readByte);
    }
}

void TcpPort::ClosePort()
{
    if (tcpPortWork != nullptr) {
        tcpPortWork->ClosePort();
    }
}
